import 'dart:convert';
import 'dart:core';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

import '../../models/downloadAPK.dart';
import '../Gesture/GestureDetectorConflictTest.dart';
import '../Gesture/GestureDetectorHitTest.dart';
import '../Gesture/NotificationInterruptTest.dart';

///三方库Dio请求的使用
class HttpDioUseDownloadProgressWidget extends StatefulWidget {
  @override
  HttpDioUseDownloadProgressState createState() {
    // TODO: implement createState
    return HttpDioUseDownloadProgressState();
  }
}

class HttpDioUseDownloadProgressState
    extends State<HttpDioUseDownloadProgressWidget> {
  late Widget buttonRequestData;
  late Widget buttonDownLoadProgress;
  late _downloadApkWidget progressWidget;
  final globalKey = GlobalKey<_downloadApkWidgetState>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    progressWidget = _downloadApkWidget(globalKey);

    buttonRequestData = ElevatedButton(
      child: Text("dio请求更新数据,请求数据"),
      onPressed: () {
        globalKey.currentState?.setHttpRequestHead();
      },
    );

    buttonDownLoadProgress = ElevatedButton(
      child: Text("dio请求，下载文件"),
      onPressed: () {
        globalKey.currentState?.downloadApk();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Column(
        children: [buttonRequestData, buttonDownLoadProgress, progressWidget],
      ),
    );
  }
}

class _downloadApkWidget extends StatefulWidget {
  _downloadApkWidget(Key? key) : super(key: key);

  @override
  _downloadApkWidgetState createState() {
    // TODO: implement createState
    return _downloadApkWidgetState(key);
  }
}

class _downloadApkWidgetState extends State<_downloadApkWidget> {

  var progress = 0.0;

  final globalKey;
  _downloadApkWidgetState(this.globalKey);

  void _getProgressValueData(int receivedBytes, int totalBytes) {
    setState(() {
      progress = receivedBytes / totalBytes;
      print("接收receivedBytes进度：$progress");
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  Dio dio = Dio();

  void setHttpRequestHead() async {
    Response<String> response = await dio.get(
        "https://admin.leke.cn/eb/admin/apk/checkUpdate",
        queryParameters: {"deviceType": "HC_TEMPERATURE", "versionCode": 1042});
    print("结果：${response.data}");

    ///常规转换 方式
    Map<String,dynamic> resultMap = json.decode(response.data!);
    ///flutter packages pub run json_model  model的插件工具生成
    var result = DownloadAPK.fromJson(resultMap);
    print("json解析结果：${result.data.toString()}");

    ///这里有错误
    // Response<BaseHttpResult> response=await dio.get("https://admin.leke.cn/eb/admin/apk/checkUpdate",queryParameters:{"deviceType":"HC_TEMPERATURE","versionCode":1042});
    // print("结果：${response.data}");
    // ///常规转换 方式
    // print("json解析结果：${response.data?.data.toString()}");
  }

  void downloadApk() async {
    Response response = await dio.download(
        "https://file.leke.cn/fs/2022-01-17/GH/HBCY/XJYZH8ORPBR3UWUV2XMSIENDTUCQRK.apk",
        '/data/user/0/com.example.first_flutter_project/app_flutter/eccard.apk',
        // _getLocalFile.toString()+"/eccard.apk",
        onReceiveProgress: (receivedBytes, totalBytes) {
      print("接收receivedBytes：${receivedBytes}---totalBytes：$totalBytes");
      _getProgressValueData(receivedBytes, totalBytes);
    });
    print("结果：${response.data}");
  }

  Future<String> _getLocalFile() async {
    // 获取应用目录对应：/data/user/0/com.example.first_flutter_project/app_flutter
    String dir = (await getApplicationDocumentsDirectory()).path;
    // String directoryPath = root.path;
    return dir;
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Row(
      children: [
        Container(
          width: 300,
          height: 10,
          color: Color(0xFF0DC2DB),
          child:  LinearProgressIndicator(
            minHeight: 10,
            backgroundColor: Colors.grey[200],
            valueColor: AlwaysStoppedAnimation(Colors.blue), // 从灰色变成蓝色
            value: progress,
          ),
        ),

        Text("${(progress*100).truncate()}%"),
      ],
    );
  }
}

class BaseHttpResult {
  int code = 0;
  String? message;
  String? time = "";
  bool? success;
  UpdateVersionBean? data;

  BaseHttpResult.fromJson(Map<dynamic, dynamic> jsonMap)
      : code = jsonMap['code'],
        time = jsonMap['time'],
        success = jsonMap['success'],
        data = UpdateVersionBean.fromJson(jsonMap['data']),
        message = jsonMap['message'];

  Map<String, dynamic> toJson() => <String, dynamic>{
        'code': code,
        'time': time,
        'success': success,
        'data': data,
        'message': message,
      };

  @override
  String toString() {
    return 'BaseHttpResult{code: $code, message: $message, time: $time, success: $success, data: $data}';
  }
}

class UpdateVersionBean {
  int versionCode = -1;
  int id = -1;
  String? versionName;
  String? updateTip;
  String? apkUrl;
  bool? isNeedUpdate;
  bool? forceUpdate;

  UpdateVersionBean.fromJson(Map<dynamic, dynamic> json)
      : versionCode = json['versionCode'],
        id = json['id'],
        versionName = json['versionName'],
        updateTip = json['updateTip'],
        apkUrl = json['apkUrl'],
        isNeedUpdate = json['isNeedUpdate'],
        forceUpdate = json['forceUpdate'];

  Map<String, dynamic> toJson() => <String, dynamic>{
        'versionCode': versionCode,
        'id': id,
        'versionName': versionName,
        'updateTip': updateTip,
        'apkUrl': apkUrl,
        'isNeedUpdate': isNeedUpdate,
        'forceUpdate': forceUpdate,
      };

  @override
  String toString() {
    return 'UpdateVersionBean{versionCode: $versionCode, id: $id, versionName: $versionName, updateTip: $updateTip, apkUrl: $apkUrl, isNeedUpdate: $isNeedUpdate, forceUpdate: $forceUpdate}';
  }
}
